//
//  HYVideoViewModel.m
//  XPlayer
//
//  Created by liguoqing on 2023/10/2.
//

#import "HYVideoViewModel.h"
#import "HYHomeFileItemViewModel.h"
#import <HYVideoPlayer/HYVideoModel.h>
#import "HYPreviewHistoryModel.h"
#import "HYFileDownloadModel.h"
#import "HYMyCollectionModel.h"

@interface HYVideoViewModel ()

@property (nonatomic, strong) NSString *folderIdentification;

@property (nonatomic, assign) BOOL isPrivate;

@end

@implementation HYVideoViewModel

- (instancetype)initWithFolderIdentification:(NSString *)folderIdentification
                                   isPrivate:(BOOL)isPrivate
                                 videoConfig:(HYVideoPlayerConfig *)videoConfig
{
    self = [super init];
    if(self){
        self.folderIdentification = folderIdentification;
        self.isPrivate = isPrivate;
        self.videoConfig = videoConfig;
        if (![folderIdentification isEqualToString:@"baidu-vplayer"] && !videoConfig.isAudioMode) {
            [self fetchPlayMemory];
        }
        self.playSubject = [RACSubject subject];
    }
    return self;
}

#pragma mark - 获取播放记忆点
- (void)fetchPlayMemory
{
    @weakify(self);
    // 判断是否开启无痕预览
    if(![HYMineSetManager shareManager].isAllowPrivateBrowse){
        [self.videoConfig.videoSoucres enumerateObjectsUsingBlock:^(HYVideoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            @strongify(self);
            [self fetchCurrentVideoPlayTimeWithModel:obj];
        }];
    }
}

- (void)readyToPlay
{
    // 1.判断视频没有收藏过，查询本地数据库是否收藏过
    HYMyCollectionModel *collectModel = [self fetchCollectModel];
    self.isCollect = collectModel?YES:NO;
    // 2.判断当前视频是否下载过
    if([self.videoConfig isLocalVideo]){
        self.isDownload = YES;
        [self.playSubject sendNext:[self.videoConfig fetchCurrentVideoUrl]];
    }else{
        NSString *sql = [NSString stringWithFormat:@"select *from DOWNLOAD where fileUrl = '%@'",[self.videoConfig fetchCurrentVideoUrl]];
        HYFileDownloadModel *model = [HYFileDownloadModel searchWithSQL:sql].firstObject;
        if(model.downloadStatus || model.progress == 1.0){//防止无法播放本地视频问题
            self.isDownload = YES;
            NSString *videoName = [model.fileUrl lastPathComponent];
            NSString *videoUrl = [HYFileManager videoDownloadPathWithFileName:videoName];
            [self.playSubject sendNext:videoUrl];
        }else{
            self.isDownload = NO;
            [self.playSubject sendNext:[self.videoConfig fetchCurrentVideoUrl]];
        }
    }
    // 保存封面方便下次获取
    if(!self.videoConfig.isCancelPlayHistory){
        if(!self.videoConfig.isAudioMode){
            [self saveVideoCoverImage];
        }
    }
}

- (void)saveVideoCoverImage
{
    NSString *imagePath = [HYFileManager videoImageSavePathWithFileName:self.videoConfig.currentVideoModel.videoImagePath];
    if(![kFileManager fileExistsAtPath:imagePath]){// 判断视频封面本地沙盒是否存在
        NSData *imageData = UIImagePNGRepresentation(self.videoConfig.currentVideoModel.videoImage);
        BOOL result = [imageData writeToFile:imagePath atomically:YES];
        if(result){
            CLog(@"视频封面保存成功");
        }
    }
}

- (void)changePlayIndex:(NSInteger)playIndex
{
    [self.videoConfig changePlayIndex:playIndex];
    [self readyToPlay];
}

- (BOOL)playLast
{
    BOOL result = [self.videoConfig playLast];
    if(result){
        [self readyToPlay];
    }
    return result;
}

- (BOOL)playNext
{
    BOOL result = [self.videoConfig playNext];
    if(result){
        [self readyToPlay];
    }
    return result;
}

- (void)changePlayMode
{
    if(self.videoConfig.playMode == HYVideoPlayOrderMode_random){
        self.videoConfig.playMode = HYVideoPlayOrderMode_default;
    }else{
        self.videoConfig.playMode ++;
    }
}

- (void)saveCurrentVideoPlayTime:(NSInteger)playTime isPlayDone:(BOOL)isPlayDone
{
    // 如开启无痕预览则不保存记录
    if([HYMineSetManager shareManager].isAllowPrivateBrowse){
        return;
    }
    HYVideoModel *videoModel = self.videoConfig.currentVideoModel;
    NSString *videoTotalTime = videoModel.videoDuration?:[self.videoConfig fetchCurrentVideoDuration];
    videoModel.memoryTime = playTime;
    videoModel.isPlayDone = isPlayDone;
    NSString *sql;
    if(self.videoConfig.isLocalVideo){
        sql = [NSString stringWithFormat:@"select * from HISTORY where videoDuration = '%@' and createDate = '%@'",videoTotalTime,videoModel.createDate];
    }else{
        sql = [NSString stringWithFormat:@"select * from HISTORY where filePath = '%@'",videoModel.videoUrl];
    }
    HYPreviewHistoryModel *historyModel = [HYPreviewHistoryModel searchWithSQL:sql].firstObject;
    if(historyModel){
        if(historyModel.videoPlayTime != playTime){
            historyModel.videoPlayTime = playTime;
            if(self.videoConfig.isLocalVideo){//防止文件移动位置后，播放路径发生变化
                historyModel.filePath = videoModel.videoUrl;
            }
            if(!historyModel.videoDuration){
                historyModel.videoDuration = [self.videoConfig fetchCurrentVideoDuration];
            }
            historyModel.updateDate = [CommUtls encodeTime:[NSDate date]];
            BOOL isSave = [historyModel updateToDB];
            if(isSave){
                CLog(@"播放记忆点保存成功");
                if (!historyModel.isPrivate) {
                    [kNotificationCenter postNotificationName:kHistroyRefreshListNotification object:nil];
                }
            }
        }
    }else{
        historyModel = [[HYPreviewHistoryModel alloc]init];
        historyModel.fileName = videoModel.videoTitle;
        historyModel.filePath = videoModel.videoUrl;
        historyModel.fileSize = videoModel.videoSize;
        historyModel.videoPlayTime = playTime;
        historyModel.videoDuration = videoModel.videoDuration;
        historyModel.videoImagePath = videoModel.videoImagePath;
        historyModel.videoDuration = videoModel.videoDuration?:[self.videoConfig fetchCurrentVideoDuration];
        historyModel.folderIdentification = self.folderIdentification?:@"";
        historyModel.folderPath = self.folderPath?:@"";
        historyModel.fileType = self.videoConfig.isAudioMode?HYHomeFileType_Audio:HYHomeFileType_Video;
        historyModel.createDate = videoModel.createDate;
        historyModel.importDate = videoModel.importDate;
        historyModel.isPrivate = self.isPrivate?YES:videoModel.isPrivate;
        historyModel.updateDate = [CommUtls encodeTime:[NSDate date]];
        BOOL isSave = [historyModel saveToDB];
        if(isSave){
            CLog(@"播放记忆点保存成功");
            if (!historyModel.isPrivate) {
                [kNotificationCenter postNotificationName:kHistroyRefreshListNotification object:nil];
            }
        }
    }
}

- (NSInteger)fetchCurrentVideoPlayTimeWithModel:(HYVideoModel *)videoModel
{
    NSString *videoTotalTime = videoModel.videoDuration?:[self.videoConfig fetchCurrentVideoDuration];
    NSString *sql;
    if([videoModel.videoUrl containsString:@"http"]){// 文件地址
        sql = [NSString stringWithFormat:@"select * from HISTORY where filePath = '%@'",videoModel.videoUrl];
    }else{// 文件大小和文件生成的日期
        sql = [NSString stringWithFormat:@"select * from HISTORY where videoDuration = '%@' and createDate = '%@'",videoTotalTime,videoModel.createDate];
    }
    HYPreviewHistoryModel *historyModel = [HYPreviewHistoryModel searchWithSQL:sql].firstObject;
    if(historyModel){
        videoModel.memoryTime = historyModel.videoPlayTime?:[CommUtls hmsToTime:videoTotalTime];
        videoModel.isPlayDone = historyModel.videoPlayTime == [CommUtls hmsToTime:videoTotalTime]?YES:NO;
        return historyModel.videoPlayTime;
    }else{
        videoModel.memoryTime = 0;
    }
    return 0;
}

- (CGFloat)currentVideoHistory
{
    // 无痕预览，不用获取记忆点
    if([HYMineSetManager shareManager].isAllowPrivateBrowse){
        return 0;
    }
    HYVideoModel *videoModel = self.videoConfig.currentVideoModel;
    return videoModel.isPlayDone?0:videoModel.memoryTime;
}

- (void)startDownloadBlock:(HYBStringBlock)downloadBlock
{
    NSString *sql = [NSString stringWithFormat:@"select *from DOWNLOAD where fileUrl = '%@'",[self.videoConfig fetchCurrentVideoUrl]];
    HYFileDownloadModel *model = [HYFileDownloadModel searchWithSQL:sql].firstObject;
    if(model){
        if(![model.folderIdentification isEqualToString:self.folderIdentification]){
            model.folderIdentification = self.folderIdentification;
            [model updateToDB];
        }else if (![model.fileName isEqualToString:[self.videoConfig fetchCurrentVideoTitle]]){
            model.fileName = [self.videoConfig fetchCurrentVideoTitle];
            [model updateToDB];
        }
        if(downloadBlock){
            downloadBlock(self.folderIdentification);
        }
    }else{
        model = [[HYFileDownloadModel alloc]initWithVideoModel:self.videoConfig.currentVideoModel isPrivate:self.isPrivate folderIdentification:self.folderIdentification];
        model.fileType = self.videoConfig.isAudioMode?1:0;
        BOOL result = [model saveToDB];
        if(result){
            if(downloadBlock){
                downloadBlock(self.folderIdentification);
            }
        }
    }
}
#pragma mark - 收藏视频
- (void)collectVideo
{
    if(self.isCollect){
        HYMyCollectionModel *collectModel = [self fetchCollectModel];
        BOOL result = [collectModel deleteToDB];
        if(result){
            self.isCollect = NO;
            [HYHub showMessage:NSLocalizedString(@"取消收藏", nil)];
        }
    }else{
        HYVideoModel *videoModel = self.videoConfig.currentVideoModel;
        HYMyCollectionModel *collectModel = [[HYMyCollectionModel alloc]init];
        collectModel.fileName = videoModel.videoTitle;
        collectModel.filePath = videoModel.videoUrl;
        collectModel.fileSize = videoModel.videoSize;
        collectModel.videoDuration = videoModel.videoDuration;
        collectModel.videoImagePath = videoModel.videoImagePath;
        collectModel.videoDuration = videoModel.videoDuration?:[self.videoConfig fetchCurrentVideoDuration];
        collectModel.folderIdentification = self.folderIdentification?:@"";
        collectModel.folderPath = self.folderPath?:@"";
        collectModel.fileType = videoModel.isAudio?HYHomeFileType_Audio:HYHomeFileType_Video;
        collectModel.createDate = videoModel.createDate;
        collectModel.importDate = videoModel.importDate;
        collectModel.isPrivate = self.isPrivate;
        collectModel.updateDate = [CommUtls encodeTime:[NSDate date]];
        BOOL isSave = [collectModel saveToDB];
        if(isSave){
            self.isCollect = YES;
            [HYHub showMessage:NSLocalizedString(@"收藏成功", nil)];
        }
    }
}

- (HYMyCollectionModel *)fetchCollectModel
{
    NSString *collectSql = [NSString stringWithFormat:@"select * from COLLECT where videoDuration = '%@' and createDate = '%@'",self.videoConfig.currentVideoModel.videoDuration?:[self.videoConfig fetchCurrentVideoDuration],self.videoConfig.currentVideoModel.createDate];
    return [HYMyCollectionModel searchWithSQL:collectSql].firstObject;
}

@end
